package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbUserMapper;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.pojo.TbUserExample;
import com.dongdongshop.service.RegisterService;
import com.dongdongshop.utils.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private TbUserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //查询用户名是否存在
    @Override
    public int findUser(String username) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> tbUsers = userMapper.selectByExample(example);
        return tbUsers.size() > 0 ? 1 : 0;
    }

    //注册功能
    @Override
    public Integer register(TbUser user, String code) {
        //判断用户手机号是否正确

        String redisCode = redisTemplate.opsForValue().get(user.getPhone());
        System.out.println(redisCode);
        if (code.equals(redisCode)){
            //验证码相等,进行注册
            user.setCreated(new Date());
            user.setUpdated(new Date());
            String salt = ShiroUtils.generateSalt(6); //生成盐
            user.setSalt(salt);
            user.setPassword(ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 3));
            return userMapper.insertSelective(user);
        }else {
            return 0;
        }

    }
}
